import React, { useRef, useState } from 'react';

import { PlusOutlined } from '@ant-design/icons';
import { ModalForm, ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Form, message, Table } from 'antd';
import { saveDataParams, proTableRequest } from '@/app/common/utils';

import { GenType } from '.';

const columns: ProColumns<GenType>[] = [
  {
    title: '表名',
    dataIndex: 'tableName',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
    search: false,
  },
  {
    title: '表描述',
    dataIndex: 'tableComment',
    valueType: 'text',
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    valueType: 'dateTime',
    sorter: true,
    hideInSearch: true,
    editable: false,
  },
  {
    title: '更新时间',
    key: 'updateTime',
    dataIndex: 'updateTime',
    valueType: 'dateTime',
    sorter: true,
    hideInSearch: true,
    editable: false,
  },
];

export default function ImportTableForm(props: { actionRef: ActionType }) {
  const actionRef = useRef<ActionType>(props.actionRef);
  const [form] = Form.useForm<GenType>();
  const [tableKeys, setTableKeys] = useState<React.Key[]>();
  return (
    <ModalForm<GenType>
      title="导入表"
      initialValues={{
        GenType: 'N',
      }}
      trigger={
        <Button type="primary">
          <PlusOutlined />
          导入表
        </Button>
      }
      form={form}
      autoFocusFirstInput
      modalProps={{
        maskClosable: false,
        destroyOnClose: true,
      }}
      submitTimeout={2000}
      onFinish={async () => {
        const res = await $post(`/tool/gen/importTable?tables=${tableKeys.join(',')}`);
        const isSuccess = res.code === 200;
        if (isSuccess) {
          message.success('导入成功');
          actionRef?.current?.reload();
        }
        return isSuccess;
      }}
    >
      <ProTable
        dateFormatter="string"
        columns={columns}
        rowKey="tableName"
        request={proTableRequest('/tool/gen/db/list')}
        pagination={{
          showQuickJumper: false,
          pageSize: 10,
        }}
        editable={{
          type: 'single',
          onDelete: async key => {
            await $delete(`/system/dict/data/${key}`);
          },
          onSave: async (_key, record) => {
            await $put(`/system/dict/data`, { ...saveDataParams(record) });
          },
        }}
        toolBarRender={false}
        search={false}
        rowSelection={{
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          onChange(selectedRowKeys, _selectedRows, _info) {
            setTableKeys(selectedRowKeys);
          },
        }}
      />
    </ModalForm>
  );
}
